package com.swpu.service_xueya.service.impl;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.swpu.service_xueya.entity.XuetangRecord;
import com.swpu.service_xueya.entity.XueyaRecord;
import com.swpu.service_xueya.entity.vo.XueyaChartData;
import com.swpu.service_xueya.entity.vo.XueyaRecordListVo;
import com.swpu.service_xueya.entity.vo.XueyaRecordVo;
import com.swpu.service_xueya.entity.vo.XueyaRecordVo2;
import com.swpu.service_xueya.mapper.XueyaRecordMapper;
import com.swpu.service_xueya.service.XueyaRecordService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author chaichai
 * @since 2024-04-17
 */
@Service
public class XueyaRecordServiceImpl extends ServiceImpl<XueyaRecordMapper, XueyaRecord> implements XueyaRecordService {

    private XueyaRecord xueyaRecord;

    @Override
    public String addXueyaData(String openid, XueyaRecord xueyaRecord) {
        xueyaRecord.setUserId(openid);
        boolean save = this.save(xueyaRecord);
        if (!save) throw new RuntimeException("保存血压失败");
        return xueyaRecord.getId();
    }

    @Override
    public XueyaRecord getXueyaDataById(String recordId) {
        XueyaRecord xueyaRecord = this.getById(recordId);
        xueyaRecord.setStatus(getXueyaStatus(xueyaRecord.getHigh(),xueyaRecord.getLow()));
        return xueyaRecord;
    }

    @Override
    public XueyaChartData getChartData(String userId) {
        List<XueyaRecordVo> recordVoList = baseMapper.getAvgHighAndLowForWeek(userId);    //查询用户血压数据高低平均值
        XueyaChartData xueyaChartData = new XueyaChartData();
        ArrayList<Integer> highList = new ArrayList<>();
        ArrayList<Integer> lowList = new ArrayList<>();
        ArrayList<Date> recordTimeList = new ArrayList<>();
        Date endTime = null;    //结束时间
        if (recordVoList.size() == 0) {    //数据为空
            endTime = DateUtil.endOfDay(new Date());
            for (int i=0;i<7;i++){
                highList.add(null);      //补全高值数据列为空
                lowList.add(null);         //补全低值数据列为空
                recordTimeList.add(DateUtil.endOfDay(endTime));
                endTime=DateUtil.offsetDay(endTime,-1);
            }
        } else if(recordVoList.size() <7) {    //数据不为空
            for(int i=0;i<recordVoList.size();i++){
                highList.add(recordVoList.get(i).getAvgHigh());
                lowList.add(recordVoList.get(i).getAvgLow());
                recordTimeList.add(DateUtil.endOfDay(recordVoList.get(i).getRecordTime()));
            }
            //结束时间点------填充
            endTime = DateUtil.endOfDay(recordVoList.get(recordVoList.size()-1).getRecordTime());
            for (int i = recordVoList.size(); i <7; i++) {    //数据库中不存在这天的数据，补全数据列为null
                highList.add(null);
                lowList.add(null);
                    endTime=DateUtil.offsetDay(endTime,-1);
                    recordTimeList.add(endTime);
            }
        }else {
            for (XueyaRecordVo xueyaRecordVo : recordVoList) {
                highList.add(xueyaRecordVo.getAvgHigh());
                lowList.add(xueyaRecordVo.getAvgLow());
                recordTimeList.add(xueyaRecordVo.getRecordTime());
            }
        }
        xueyaChartData.setRecordTime(recordTimeList);
        xueyaChartData.setAvgHigh(highList);
        xueyaChartData.setAvgLow(lowList);
        return xueyaChartData;
    }

    @Override
    public List<XueyaRecordListVo> getXueyaDataList(String openid, Integer pageNum, Integer pageSize) {
        int start=(pageNum-1)*pageSize;
        List<XueyaRecordVo2> recordList =   baseMapper.getXueyaDataList(openid,start,pageSize);
        ArrayList<XueyaRecordListVo> resultList = new ArrayList<>();
        Date recordDate=null;
        int i=0;
        for (i=0;i<recordList.size();) {
            XueyaRecordVo2 record = recordList.get(i);
            if(recordDate==null||record.getRecordDate().getTime()!=recordDate.getTime()){
                recordDate=record.getRecordDate();
                XueyaRecordListVo xueyaRecordListVo = new XueyaRecordListVo();
                xueyaRecordListVo.setRecordDate(record.getRecordDate());
                ArrayList<XueyaRecordVo2> nowDateXueyaRecordList = new ArrayList<>();
                for(int j=i;j<recordList.size();){
                    if(recordList.get(j).getRecordDate().getTime()==recordDate.getTime()){
                        XueyaRecordVo2 xueyaRecord1 = new XueyaRecordVo2();
                        xueyaRecord1.setStatus(getXueyaStatus(recordList.get(j).getHigh(),recordList.get(j).getLow()));
                        xueyaRecord1.setRecordTime(recordList.get(j).getRecordTime());
                        xueyaRecord1.setHigh(recordList.get(j).getHigh());
                        xueyaRecord1.setLow(recordList.get(j).getLow());
                        xueyaRecord1.setMaibo(recordList.get(j).getMaibo());
                        nowDateXueyaRecordList.add(xueyaRecord1);
                    }else {
                        i=j;
                        break;
                    }
                    j++;
                    if(j==recordList.size()){
                        i=j;
                    }
                }
                xueyaRecordListVo.setRecordList(nowDateXueyaRecordList);
                resultList.add(xueyaRecordListVo);
            }
        }
        return  resultList;
    }
    //获取最近30天的血压情况
    @Override
    public Map getRecentMonthXueyaStatus(String openid) {
        Date date = new Date();
        DateTime endDate = DateUtil.endOfDay(date);
        DateTime startDate = DateUtil.offsetDay(endDate, -30);
        LambdaQueryWrapper<XueyaRecord> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(XueyaRecord::getUserId,openid);
        queryWrapper.between(XueyaRecord::getRecordTime,startDate,endDate);
        List<XueyaRecord> recordList = this.list(queryWrapper);
        HashMap<String, Object> map = new HashMap<>();
        map.put("total",recordList.size());
        int count=0;
        for (XueyaRecord record : recordList) {
            if(getXueyaStatus(record.getHigh(),record.getLow())==0){
                count++;
            }
        }
        map.put("normal",count);
        return map;
    }

    @Override
    public XueyaRecord getXueyaDataNewest(String openid) {
        LambdaQueryWrapper<XueyaRecord> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(XueyaRecord::getUserId,openid).orderByDesc(XueyaRecord::getRecordTime);
        Date date = new Date();
        DateTime beginOfDay = DateUtil.beginOfDay(date);
        DateTime endOfDay = DateUtil.endOfDay(date);
        queryWrapper.between(XueyaRecord::getRecordTime,beginOfDay,endOfDay);
        XueyaRecord record = this.getOne(queryWrapper);
        Integer status = getXueyaStatus(record.getHigh(), record.getLow());
        record.setStatus(status);
        return record;
    }



    public Integer getXueyaStatus(Integer high,Integer low){
        //收缩压低于90mmHg，舒张压低于60mmHg
        if(high<90||low<60){
            return -1;
        }
        else if(high<140&&high>=90&&low<90&&low>=60){
            return 0;
        }
        //收缩压140-159mmHg和（或）舒张压90-99mmHg为1级高血压，
        // 收缩压160-179mmHg和（或）舒张压100-109mmHg为2级高血压，
        // 收缩压≥180mmHg和（或）舒张压≥110mmHg为3级高血压。
        else if((high>=140&&high<=159&&low<90)||(high<140&&low>=90&&low<=99)||(high>=140&&high<=159&&low>=90&&low<=99)){
            return 1;
        }else if((high>=160&&high<=179&&low<110)||(high<160&&low>=100&&low<=109)||(high>=160&&high<=179&&low>=100&&low<=109)){
            return 2;
        }else if((high>=180)||(low>=110)){
            return 3;
        }
        return 0;
    }

}
